package com.duoduo.devtools.generator;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URL;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import com.duoduo.devtools.util.MetadataUtil;
import com.duoduo.devtools.vo.JavaBeanGenerate;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.SneakyThrows;

public class CodeGenerator {
	    protected Configuration cfg;//Freemarker配置对象
	    protected Template controller;//ftl模板对象
	    protected Template entity;//ftl模板对象
	    protected Template service;//ftl模板对象
	    protected Template repsitory;//ftl模板对象
	    protected JavaBeanGenerate  javaBeanGenerate ;//要填充到模板的数据
	    protected String projectPath;
	    protected String apiPath;
	    

	    //构造方法
	    @SneakyThrows
	    public CodeGenerator(Class czz){
	    	// 模板存放在 resources 下的 templates 目录下
	        cfg = new Configuration(Configuration.getVersion());//Freemarkey配置对象
	        
			   String objPath = new ClassPathResource("").getURI().getPath();
			   String[] paths = objPath.split("/");
		
			   StringBuffer befURL = new StringBuffer();
			   for (int i = 1; i < 5; i++) {
				   befURL.append(paths[i]);
				   befURL.append(File.separator);
			   }
			   String projectUrl = befURL.toString()+"src"+File.separator+"main";
			   String  apiUrl = befURL.toString()+paths[5]+File.separator+"src"+File.separator+"main";
	        apiPath  = apiUrl +File.separator +"java";
	        projectPath  = projectUrl +File.separator +"java";
	        cfg.setClassForTemplateLoading(CodeGenerator.class, "/templates");
	        //获取所有信息
	        javaBeanGenerate = MetadataUtil.getParam(czz);
	        controller = cfg.getTemplate("Controller.ftl");
	        entity = cfg.getTemplate("Entity.ftl");
	        service = cfg.getTemplate("Service.ftl");
	        repsitory = cfg.getTemplate("Repository.ftl");
	    }
	
	    @SneakyThrows
	    public void generateClass() {
	    	  //确定路径
	    	String packageUrl = javaBeanGenerate.getPath();
	        String fileUrl = projectPath +File.separator +javaBeanGenerate.getPath();
	        String apiFileUrl = apiPath +File.separator +javaBeanGenerate.getPath()+File.separator+"api";
	        //生成 controller
	    	this.generateCode(controller, fileUrl+File.separator+"controller", "Controller");
	        //生成 entity
	    	this.generateCode(entity, apiFileUrl+File.separator+"entity", "");
	        //生成 repository
	    	this.generateCode(repsitory, fileUrl+File.separator+"repository", "Repository");
	        //生成 service
	    	this.generateCode(service, fileUrl+File.separator+"service", "Service");
	    	
	    }
	    //生成代码的方法
	    public void generateCode(Template template,String fileUrl,String fileName) throws Exception{
	        System.out.println("-----------开始生成"+template.getName()+"代码");
	        OutputStreamWriter writer = null;
            try {
            	 File dir = new File(fileUrl);
                 if(!dir.exists()){
                 dir.mkdirs();
                 }
                //生成的每个代码文件，拼接文件名，创建一个文件写入器
                writer = new FileWriter(fileUrl+"/"+javaBeanGenerate.getEntityType()+fileName+".java");
                //Freemarker合成数据和模板，输出带代码文件
                template.process(javaBeanGenerate,writer);
                //清空写入器缓冲
                writer.flush();
            }catch (TemplateException e){
                e.printStackTrace();
            }catch (IOException e){
                e.printStackTrace();
            }finally {
                try {
                    writer.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
	        System.out.println("根据"+template.getName()+"模板生成代码成功！\n\n");
	    }
}
